package com.spsy.pay.config;

import com.spsy.pay.constant.RabbitMqConstantCompany;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Configuration;

/**
 * @author 沈昕希  &&  (=￣ω￣=)m
 * @Shen "再说错了又能怎么样呢？人生不就是由无数的错误组成的吗"
 * @xin "我是个无聊的人，我有无数的缺点，我也并不喜欢我自己，甚至厌恶我自己"
 * @date 2025/9/26-16:48
 */
@Configuration
public class RabbitMqConfigCompany {

    @Bean
    public Queue createQueue(){
        return new Queue(RabbitMqConstantCompany.MQ_NAME,true);
    }

    @Bean
    public DirectExchange createExchange(){
        return new DirectExchange(RabbitMqConstantCompany.MQ_EXCHANGE);
    }

    @Bean
    public Binding bindingCompany(){
        return BindingBuilder.bind(createQueue()).to(createExchange()).with(RabbitMqConstantCompany.MQ_ROUTTING);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack){
                System.out.println("消息发送成功="+correlationData.getId());
            }else {
                System.out.println("消息发送失败，原因:"+cause+",消息ID="+correlationData.getId());
            }

        });

        rabbitTemplate.setReturnsCallback(returned -> {
            System.out.println("错误码- ReplyCode="+returned.getReplyCode());
            System.out.println("错误原因- replyText="+returned.getReplyText());
            System.out.println("交换机- exchange="+returned.getExchange());
            System.out.println("routingKey="+returned.getRoutingKey());
            System.out.println("消息-="+new String(returned.getMessage().getBody()));
        });
        return rabbitTemplate;
    }




}
